package net.a6polo.renren;


import java.io.File;
import java.io.FileNotFoundException;

import net.a6polo.a6poloweibo.util.RenrenParamer;
import net.a6polo.renren.domain.PhotosUploadResponse;
import net.a6polo.renren.domain.ResultResponse;
import net.a6polo.renren.net.RequestListener;
import net.a6polo.renren.ui.RenrenFeedActivity;
import net.a6polo.service.Service;
import net.a6polo.service.SnsType;
import net.a6polo.service.domain.Account;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.StringPart;

import com.google.gson.Gson;

import android.content.Context;
import android.util.Log;

public class RenrenAPIV2 {
	public static final String API_URL = "http://api.renren.com/restserver.do";
	public static final String v = "1.0";

	private String token;
	private String refresh_token;

	public RenrenAPIV2(Context ctx) {
		Service service = new Service(ctx);
		Account renrenAccount = service.getLastAccountByType(SnsType.RENREN);
		token = renrenAccount.getAccessToken();
		refresh_token = renrenAccount.getRefreshToken();
	}

	public void getFeed(int page, int count, final RequestListener listener) {
		String requestMethod = "feed.get";
		String url = API_URL;

		// type 描述
		// 10 更新状态的新鲜事。
		// 11 page更新状态的新鲜事。
		// 20 发表日志的新鲜事。
		// 21 分享日志的新鲜事。
		// 22 page发表日志的新鲜事。
		// 23 page分享日志的新鲜事。
		// 30 上传照片的新鲜事。
		// 31 page上传照片的新鲜事。
		// 32 分享照片的新鲜事。
		// 33 分享相册的新鲜事。
		// 34 修改头像的新鲜事。
		// 35 page修改头像的新鲜事。
		// 36 page分享照片的新鲜事。
		// 40 成为好友的新鲜事。
		// 41 成为page粉丝的新鲜事。
		// 50 分享视频的新鲜事。
		// 51 分享链接的新鲜事。
		// 52 分享音乐的新鲜事。
		// 53 page分享视频的新鲜事。
		// 54 page分享链接的新鲜事。
		// 55 page分享音乐的新鲜事。

		String typeList = "10,11,20,21,22,23,30,32,32,33,43,35,36,40,41,50,51,52,53,54,55";

		// 生成签名
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=").append(token)
		  .append("count=").append(count)
		  .append("format=").append("JSON")
		  .append("method=").append(requestMethod)
		  .append("page=").append(page)
		  .append("type=").append(typeList)
		  .append("v=").append(v)
		  .append(RenrenParamer.secret);
		
		String signature = MD5.getMD5(sb.toString());
		
		final PostMethod method = new PostMethod(url);

		method.addParameter("access_token", token);
		method.addParameter("format", "JSON");
		method.addParameter("method", requestMethod);
		method.addParameter("v", v);
		method.addParameter("type", typeList);
		method.addParameter("page", page+"");
		method.addParameter("count", count+"");
		method.addParameter("sig", signature);
		
		new Thread() {
			@Override
			public void run() {
				HttpClient client = new HttpClient();
				try {
					client.executeMethod(method);
					String json = method.getResponseBodyAsString(); // 返回请求的结果
					Log.d("a6polo", "renrenAPIV2 result getFeed --- :" + json);
					listener.onComplete(json);
					
				} catch (Exception e) {
					e.printStackTrace();
					listener.onError(e);
				}
			}
		}.start();
	}


	public void getUserInfo(final RequestListener listener) {
		String requestMethod = "users.getInfo";
		String url = API_URL;
		
		// 生成签名
				StringBuilder sb = new StringBuilder();
				sb.append("access_token=").append(token)
				  .append("format=").append("JSON")
				  .append("method=").append(requestMethod)
				  .append("v=").append(v)
				  .append(RenrenParamer.secret);
				
		String signature = MD5.getMD5(sb.toString());
				
		final PostMethod method = new PostMethod(url);
		
		method.addParameter("access_token", token);
		method.addParameter("format", "JSON");
		method.addParameter("method", requestMethod);
		method.addParameter("v", v);
		method.addParameter("sig", signature);
		
		new Thread() {
			@Override
			public void run() {
				HttpClient client = new HttpClient();
				try {
					client.executeMethod(method);
					String json = method.getResponseBodyAsString(); // 返回请求的结果
					Log.d("a6polo", "renrenAPIV2 result:" + json);
					listener.onComplete(json);
					
				} catch (Exception e) {
					e.printStackTrace();
					listener.onError(e);
				}
			}
		}.start();
	}
	
	public void refreshToken(final RequestListener listener) {		
		String url = "https://graph.renren.com/oauth/token?grant_type=refresh_token&" +
				"refresh_token="+refresh_token+"&client_id="+RenrenParamer.apiKey+"&" +
						"client_secret="+RenrenParamer.secret;
		final PostMethod method = new PostMethod(url);
		
		new Thread() {
			@Override
			public void run() {
				HttpClient client = new HttpClient();
				try {
					client.executeMethod(method);
					String json = method.getResponseBodyAsString(); // 返回请求的结果
					Log.d("a6polo", "renrenAPIV2 result:" + json);
					listener.onComplete(json);
					
				} catch (Exception e) {
					e.printStackTrace();
					listener.onError(e);
				}
			}
		}.start();
	}
	
	public void updateStatus(String status, final RequestListener listener) {
		String requestMethod = "status.set";
		String url = API_URL;

		// String statusUrl = URLEncoder.encode(status);

		// 生成签名
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=").append(token).append("format=").append("JSON").append("method=")
				.append(requestMethod).append("status=").append(status).append("v=").append(v)
				.append(RenrenParamer.secret);
		String signature = MD5.getMD5(sb.toString());
		final UTF8PostMethod method = new UTF8PostMethod(url);
		// 将以上准备好的参数添加到method对象中
		method.addParameter("access_token", token);
		method.addParameter("method", requestMethod);
		method.addParameter("v", v);
		method.addParameter("status", status);
		method.addParameter("format", "JSON"); // 返回结果的形式，支持XML或者JSON两种形式，默认为XML
		method.addParameter("sig", signature);
	
		new Thread() {
			@Override
			public void run() {
				HttpClient client = new HttpClient();
				try {
					client.executeMethod(method);
					String json = method.getResponseBodyAsString(); // 返回请求的结果
					Log.d("a6polo", "result:" + json);
					listener.onComplete(json);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
		

//		Gson gson = new Gson();
//		ResultResponse result = gson.fromJson(json, ResultResponse.class);
//		if (result.getResult().equals("1")) {
//			return true;
//		} else {
//			return false;
//		}
	}
	
	public void photoUpload(String caption, String picPath, final RequestListener listener) {
		String requestMethod = "photos.upload";
		String url = API_URL;
		File file = new File(picPath);

		// 生成签名
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=").append(token).append("caption=").append(caption).append("format=").append("JSON")
				.append("method=").append(requestMethod).append("v=").append(v).append(RenrenParamer.secret);
		String signature = MD5.getMD5(sb.toString());

		final MultipartPostMethod method = new MultipartPostMethod(url);
		method.setRequestHeader("Content-type", "multipart/form-data; boundary=SoMeTeXtWeWiLlNeVeRsEe");

		// 将以上准备好的参数添加到method对象中
		method.addParameter("access_token", token);
		method.addParameter("method", requestMethod);
		method.addParameter("v", v);
		method.addParameter("format", "JSON"); // 返回结果的形式，支持XML或者JSON两种形式，默认为XML
		method.addParameter("sig", signature);
		// method.addParameter("caption", caption);
		try {
			method.addParameter("upload", file);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		StringPart namePart = new StringPart("caption", caption);// 对于简单的值对都这样处理
		namePart.setCharSet("UTF-8");// 注意要设置编码，与你处理请求的代码中设置的一样
		method.addPart(namePart);

		new Thread() {
			@Override
			public void run() {
				HttpClient client = new HttpClient();

				try {
					client.executeMethod(method);
					String json = method.getResponseBodyAsString(); // 返回请求的结果
					Log.d("a6polo", "result:" + json);
					listener.onComplete(json);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	

//		Gson gson = new Gson();
//		return gson.fromJson(json, PhotosUploadResponse.class);
	}
}
